import { EventBus } from "feok-lib";

export const emitError = (options: any = {}) => {
  return async function fn(m: any, next: any) {
    if (m.res) {
      const code = m.res.data ? m.res.data.code : m.res.code;
      const msg = m.res.data ? m.res.data.msg : m.res.message;
      // if (code * 1 > 100000) {
      if (code * 1 !== 100000) {
        switchErrors(code, msg, options);
        throw new Error(msg);
      }
      next();
    }
  };
};

export const switchErrors = (code: number, msg: string, options: any) => {
  switch (code) {
    case 502:
      EventBus.$emit("error", "服务器异常，请稍后再试！");
      break;
    case 401:
      EventBus.$emit("loginInvalid");
      break;
    case 3002:
      EventBus.$emit("loginInvalid");
      break;
    default:
      options.emit !== false && EventBus.$emit("error", msg);
      break;
  }
};
